package cn.my.learning.web;

import cn.my.learning.domain.Library;
import cn.my.learning.domain.LibraryList;
import cn.my.learning.domain.User;
import cn.my.learning.repository.UserRepository;
import cn.my.learning.service.LibraryDetailServiceImpl;
import cn.my.learning.service.LibraryServiceImpl;
import cn.my.learning.util.IsLoginUtil;
import cn.my.learning.util.MD5Util;
import com.mongodb.WriteResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Created by ML on 2017/3/13.
 * Updated by Leo on 2017/3/28
 * 文库页面管理类
 */
@Controller
public class LibraryController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private LibraryServiceImpl libraryService;

    @Autowired
    private LibraryDetailServiceImpl LibraryDetailService;

    //MongoTemplate
    @Autowired
    private MongoTemplate mongoTemplate;

    //Logger日志
    private static final Logger logger = LoggerFactory.getLogger(LibraryController.class);

    //初始化提交次数
    private int post_number = 1;

    //初始化MD5Util类，并通过文章内容进行MD5获取
    MD5Util md5Util = new MD5Util();

    //初始化两个list，一个用来存文章，一个用来存MD5的值
    List<LibraryList> lib_list = new ArrayList<LibraryList>();
    List<String> articleMD5UtilList = new ArrayList<String>();
    List<String> titleMD5UtilList = new ArrayList<String>();

    //实现方法
    @ApiOperation(value = "跳转到码猿文库页面", httpMethod = "GET", notes = "跳转到码猿文库页面")
    @RequestMapping(value = "/my_library")
    public String listLibrary(HttpServletRequest httpServletRequest) {
        if (httpServletRequest.getRemoteUser() != null){
            User user = userRepository.findUsernameByAccount(httpServletRequest.getRemoteUser());
            httpServletRequest.setAttribute("Username", user.getUsername());
        }
        return "my_library";
    }

    @ApiOperation(value = "跳转到发布文章页面", httpMethod = "GET", notes = "跳转到发布文章页面")
    @RequestMapping(value = "/writeArticle")
    public String listLibraryDetail(HttpServletRequest httpServletRequest) {
        //GET方法变量初始化（解决重复提交后刷新页面提交次数的值还在内存当中）
        String userName = new IsLoginUtil().IsLogin(httpServletRequest);
        if (!Objects.equals(userName, "未登录用户")){
            User user = userRepository.findUsernameByAccount(httpServletRequest.getRemoteUser());
            httpServletRequest.setAttribute("Username", user.getUsername());
            post_number = 1;
            lib_list = new ArrayList<LibraryList>();
            articleMD5UtilList = new ArrayList<String>();
            titleMD5UtilList = new ArrayList<String>();
            return "writeArticle";
        }
        return "redirect:/my_home";
    }

    @ApiOperation(value = "跳转到编辑文章页面", httpMethod = "GET", notes = "跳转到编辑文章页面")
    @RequestMapping(value = "/updateArticle/{userAccount}/{articleCode}")
    public String getUpdateArticle(HttpServletRequest httpServletRequest){
        User user = userRepository.findUsernameByAccount(httpServletRequest.getRemoteUser());
        httpServletRequest.setAttribute("Username", user.getUsername());
        return "updateArticle";
    }

    @ApiOperation(value = "获取对应libraryType的书库类型", httpMethod = "GET", notes = "获取对应libraryType的书库类型")
    @RequestMapping(value = "get_my_library")
    @ResponseBody
    public Page<Library> getLibrarys(@RequestParam String libraryType,@RequestParam Integer currentPage,@RequestParam Integer size) {
        return libraryService.findLibraryType(libraryType,currentPage, size);
    }

    @ApiOperation(value = "通过libraryCode查找对应的书库类型", httpMethod = "GET", notes = "通过libraryCode查找对应的类型")
    @RequestMapping(value = "get_one_library")
    @ResponseBody
    public List<Library> getLibrary(@RequestParam String libraryCode){
        //构建分页信息
        return libraryService.findLibraryCode(libraryCode);
    }

    @ApiOperation(value = "添加一篇文章", httpMethod = "POST", notes = "添加一篇文章", response = boolean.class)
    @RequestMapping(value = "add_library_article")
    @ResponseBody
    public boolean addBasicInfo(@ApiParam(required = true, name = "libraryList", value = "获取修改LibraryList对象") @RequestBody LibraryList libraryList, HttpServletRequest httpServletRequest) {

        //用户账户名
        String account = httpServletRequest.getSession().getAttributeNames().toString();

        //传入文章来源
        libraryList.setArticleOrigin("码猿");

        //传入文章提交时间
        libraryList.setArticleDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        //获得文章和标题的MD5
        String articleMD5 = md5Util.getMD5String(libraryList.getArticle());
        String articleTitleMD5 = md5Util.getMD5String(libraryList.getArticleTitle());

        //对象中set入文本MD5，文本标题MD5
        libraryList.setArticleMD5(articleMD5);
        libraryList.setArticleTitleMD5(articleTitleMD5);

        //传入articleMD5去数据库查询是否有相同的数据,相同数据以Count方法返回的条目数
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("articleMD5").is(articleMD5), Criteria.where("publisherAccount").is(account));
        final long articleMD5_count_number = mongoTemplate.count(new Query(criteria), LibraryList.class);

        //判断返回值，即是否存在同一用户有两个相同的文章
        if (articleMD5_count_number != 1){
            mongoTemplate.insert(libraryList);
            return true;
        }
        else {
            return false;
        }
    }

    @ApiOperation(value = "删除一篇文章", httpMethod = "POST", notes = "删除一篇文章", response = boolean.class)
    @RequestMapping(value = "delete_user_library")
    @ResponseBody
    public boolean deleteUserLibrary(@RequestParam String articleCode, @RequestParam HttpServletRequest httpServletRequest){

        String account = new IsLoginUtil().IsLogin(httpServletRequest);

        //执行删除语句
        Criteria criteria = new Criteria();
        criteria.andOperator(Criteria.where("publisherAccount").is(account), Criteria.where("articleCode").is(articleCode));
        WriteResult writeResult = mongoTemplate.remove(new Query(criteria), LibraryList.class);

        //返回是否删除成功
        return writeResult.isUpdateOfExisting();
    }

    @ApiOperation(value = "更新一篇文章", httpMethod = "POST", notes = "更新一篇文章", response = boolean.class)
    @RequestMapping(value = "update_user_library")
    @ResponseBody
    public boolean updateUserLibrary(@ApiParam(required = true, name = "UpdateUserLibrary", value = "更新LibraryList对象") @RequestBody LibraryList libraryList){
        //查询出where传过来的文章在数据库是否有这个对象
        Query query = Query.query(Criteria.where("articleCode").is(libraryList.getArticleCode()));

        //编写Update操作
        Update update = Update.update("article", libraryList.getArticle())
                                    .set("articleTag",libraryList.getArticleTag())
                                    .set("articleDate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
                                    .set("libraryCode", libraryList.getLibraryCode())
                                    .set("articleTitle", libraryList.getArticleTitle())
                                    .set("articleUrl", libraryList.getArticleUrl())
                                    .set("libraryName", libraryList.getLibraryName());

        //执行查询语句并update
        WriteResult writeResult = mongoTemplate.updateFirst(query, update, LibraryList.class);

        //返回修改状态（是否成功修改）
        return writeResult.isUpdateOfExisting();
    }
}
